<template>
  <div class="review-card" :style="{ backgroundColor: props.backgroundColor }">
    <div class="tabs">
      <a-tabs v-model:activeKey="activeKey" :tab-bar-style="{ color: '#191930BF', marginBottom: '24px' }">
        <a-tab-pane v-for="tab in tabs" :key="tab.key" :tab="tab.name">
          <a-space direction="vertical" class="w-[100%]">
            <!-- API服务 -->
            <template v-if="activeKey === '1'">
              <a-collapse v-for="apiItem in props.auditAppApi" :key="apiItem.id">
                <template #expandIcon="{ isActive }">
                  <caret-right-outlined :rotate="isActive ? 90 : 0" :style="{ color: '#19193073' }" />
                </template>
                <a-collapse-panel key="1" :style="{ background: '#fff' }">
                  <template #header>
                    <a-row class="my-a-collapse-header" :align="'middle'">
                      <a-col class="header-title">{{ apiItem.algoName }}</a-col>

                      <a-col flex="1" />
                      <!-- <a-col @click.stop=""> 已选择{{ apiItem.algoName }}</a-col> -->
                    </a-row>
                  </template>
                  <a-table
                    :style="{ width: '100%', borderRadius: 0 }"
                    :scroll="{ x: 'auto' }"
                    :columns="apiTableColumns"
                    :data-source="apiItem.appServeList"
                    :pagination="false"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex == 'totalCallNum'">
                        <div v-if="!record.addTotalCallNum" :title="record.totalCallNum">{{ record.totalCallNum }}</div>
                        <div v-else class="adjustmentAmount" :title="record.totalCallNum">
                          <span>{{ record.totalCallNum }}</span>
                          <i class="icon-arrow-up-s-fill iconfont newStatus"></i>
                          <span class="newStatus"> {{ record.addTotalCallNum }}</span>
                        </div>
                      </template>
                      <template v-else-if="column.dataIndex == 'qps'">
                        <div v-if="!record.addQps">{{ record.qps }}</div>
                        <div v-else class="adjustmentAmount">
                          <span>{{ record.qps }}</span>
                          <i class="icon-arrow-up-s-fill iconfont newStatus"></i>
                          <span class="newStatus"> {{ record.addQps }}</span>
                        </div>
                      </template>
                      <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                    </template>
                  </a-table>
                </a-collapse-panel>
              </a-collapse>
              <div v-if="auditAppApi?.length === 0">
                <a-empty :image="simpleImage" />
              </div>
            </template>
            <!-- SDK服务 -->
            <template v-else-if="activeKey === '2'">
              <a-collapse v-for="askItem in props.auditAppSdk" :key="askItem.id">
                <template #expandIcon="{ isActive }">
                  <caret-right-outlined :rotate="isActive ? 90 : 0" :style="{ color: '#19193073' }" />
                </template>
                <a-collapse-panel key="1" :style="{ background: '#fff' }">
                  <template #header>
                    <a-row class="my-a-collapse-header" :align="'middle'">
                      <a-col class="header-title">{{ askItem.algoName }}</a-col>

                      <a-col flex="1" />
                      <!-- <a-col @click.stop=""> 已选择{{ askItem.algoName }}</a-col> -->
                    </a-row>
                  </template>
                  <a-table
                    :style="{ width: '100%', borderRadius: 0 }"
                    :scroll="{ x: 'auto' }"
                    :columns="sdkTableColumns"
                    size="small"
                    :data-source="askItem.appServeList"
                    :pagination="false"
                  >
                    <template #bodyCell="{ column, record }">
                      <template v-if="column.dataIndex == 'authType'">
                        {{ record.authType === 1 ? '联网激活' : '离线激活' }}
                      </template>
                      <template v-else-if="column.dataIndex == 'totalActivateNum'">
                        <div v-if="!record.addTotalActivateNum">{{ record.totalActivateNum }}</div>
                        <div v-else class="adjustmentAmount">
                          <span>{{ record.totalActivateNum }}</span>
                          <i class="icon-arrow-up-s-fill iconfont newStatus"></i>
                          <span class="newStatus"> {{ record.addTotalActivateNum }}</span>
                        </div>
                      </template>
                      <template v-else-if="column.dataIndex == 'fileName'">
                        {{ record.addFileName && record.addTotalActivateNum ? record.addFileName : record.fileName }}
                      </template>
                      <template v-else-if="column.dataIndex == 'operate'">
                        <div v-if="record.authType === 2">
                          <i class="cursor-pointer icon-download-2-line iconfont" @click.stop="handleDownload(record.id)"></i>
                          <i
                            class="ml-5 cursor-pointer icon-search-line iconfont"
                            @click.stop="handlePreview(record as AuditAppSdkVOList)"
                          ></i>
                        </div>
                      </template>
                      <template v-else> {{ replaceEmptyStr(record[column.dataIndex as string]) }} </template>
                    </template>
                  </a-table>
                </a-collapse-panel>
              </a-collapse>
              <div v-if="auditAppSdk?.length === 0">
                <a-empty :image="simpleImage" />
              </div>
            </template>
          </a-space>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
  <a-modal
    :open="previewVisible"
    :footer="null"
    get-container=".tabs"
    width="988px"
    :body-style="{ background: '#F2F2F5', borderRadius: '4px' }"
    @cancel="handleCancel"
  >
    <template #title>
      <div class="modalTitle" :title="previewTitle">{{ previewTitle }}</div>
    </template>
    <div class="example">
      <a-spin :spinning="loadingShow" tip="加载中">
        <p class="preview-text">{{ previewTxt }}</p>
      </a-spin>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { message } from 'ant-design-vue'
  import { Empty } from 'ant-design-vue'
  import { debounce } from 'g6-fn'
  import { computed, onMounted, ref, watch } from 'vue'
  import { useRoute } from 'vue-router'

  import manualMessage from '@/components/ManualMessage/index'
  import { applicationAuditApi, clientApi, fetchDownload } from '@/services/api'
  import { filterTableColumns, replaceEmptyStr } from '@/utils'

  import { AuditAppSdkVOList } from '../types/index'

  const props = defineProps({
    auditAppApi: {
      type: Object,
      default: () => {}
    },
    auditAppSdk: {
      type: Object,
      default: () => {}
    },
    // 组件使用场景，life:生活周期，check:审核
    cType: {
      type: String,
      default: 'check'
    },
    backgroundColor: {
      type: String,
      default: '#fff'
    }
  })
  const route = useRoute()
  const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE

  const appId = (route.params.id as string) || ''
  const activeKey = ref<'1' | '2'>('1')
  const tabs = computed(() => [
    {
      key: '1',
      name: `API服务`
    },
    {
      key: '2',
      name: `SDK服务`
    }
  ])
  // const tabs = ref<Record<string, string>[]>([])

  // const init = () => {
  //   if (props.auditAppApi?.length) {
  //     console.log('有api', props.auditAppApi.length)
  //     tabs.value.push({
  //       key: '1',
  //       name: `API服务`
  //     })
  //   }

  //   if (props.auditAppSdk?.length) {
  //     console.log('有sdk', props.auditAppSdk)
  //     tabs.value.push({
  //       key: '2',
  //       name: `SDK服务`
  //     })
  //   }
  // }
  // defineExpose({
  //   init
  // })

  const emits = defineEmits(['getClientInfo'])

  watch(
    () => activeKey.value,
    () => emits('getClientInfo', appId),
    { immediate: true }
  )

  /* API,SDK展示逻辑-------------------------------------------------------------------- */
  const apiTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version'
        // width: 400
      },
      {
        title: '调用量',
        dataIndex: 'totalCallNum',
        width: 128
      },
      {
        title: 'QPS',
        dataIndex: 'qps',
        width: 128
      }
    ])
  )
  const sdkTableColumns = ref(
    filterTableColumns([
      {
        title: '版本号',
        dataIndex: 'version'
        // width: 76
      },
      {
        title: '平台',
        dataIndex: 'platform',
        minWidth: 148
      },
      {
        title: '语言',
        dataIndex: 'language'
        // width: 76
      },
      {
        title: '授权方式',
        dataIndex: 'authType'
        // width: 76
      },
      {
        title: '可激活设备数',
        dataIndex: 'totalActivateNum'
        // align: 'center'
        // width: 128
      },
      {
        title: '机器指纹文件',
        dataIndex: 'fileName',
        minWidth: 148
      },
      {
        title: '',
        dataIndex: 'operate',
        width: 54
      }
    ])
  )

  //下载指纹文件
  const handleDownload = debounce(async (taskId: string): Promise<void> => {
    manualMessage.loading('数据准备中,请耐心等待...', 0)

    try {
      let downloadApi = props.cType === 'check' ? applicationAuditApi.downloadFiles : clientApi.downloadFingerprint

      const { data } = await downloadApi(
        {},
        {
          urlParams: { id: taskId },
          isResponseAll: true,
          timeout: 300000 //设置超时时长5min
        }
      )

      await fetchDownload(data.data.fileUrl, `${data.data.fileName}`)
      manualMessage.destroy()
      await message.success({ content: '文件下载成功', key: 'downloading', duration: 2 })
      console.log('下载成功')
    } catch (error) {
      console.log('下载失败', error)
      manualMessage.destroy()
      message.error({ content: '文件下载失败', key: 'downloading', duration: 2 })
    }
  }, 500)

  //预览
  const previewVisible = ref<boolean>(false)
  const previewTitle = ref<string>('')
  const previewTxt = ref<string>('')
  const previewCategory = ref<string>('')
  const loadingShow = ref<boolean>(false)
  //预览指纹文件
  const handlePreview = async (row: AuditAppSdkVOList): Promise<void> => {
    loadingShow.value = true
    previewVisible.value = true

    previewCategory.value = row.fileName?.split('.').pop()?.toLowerCase() || ''
    const { data } = await applicationAuditApi.previewFiles({}, { urlParams: { id: row.id } })
    previewTitle.value = data.fileName || ''
    previewTxt.value = data.fileContent || ''
    loadingShow.value = false
  }

  const handleCancel = () => {
    previewVisible.value = false
    previewTitle.value = ''
    previewTxt.value = ''
    previewCategory.value = ''
  }
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .review-card {
    display: flex;
    padding: 20px;
    margin-bottom: 32px;
    width: 100%;
    background: #fff;
    border-radius: 8px;

    .tabs {
      flex: 1;
      // height: 100%;
      display: flex;
      overflow: hidden;

      :deep(.ant-tabs-tab-active .ant-tabs-tab-btn) {
        font-weight: 600;
        color: rgba(16, 16, 20, 0.95);
      }

      .ant-tabs {
        width: 100%;

        :deep(.ant-tabs-content-holder) {
          overflow-y: auto;
        }
      }

      .ant-collapse {
        width: 100%;

        :deep(.ant-collapse-content-box) {
          padding: 0;
        }
      }

      .iconfont {
        color: #009cf8;
      }

      .header-title {
        font-size: 14px;
        color: rgba(16, 16, 20, 0.95);
        font-weight: 700;
        line-height: 22px;
      }
    }
    // .max-width {
    //   max-width: 200px;
    //   overflow: hidden;
    //   text-overflow: ellipsis;
    //   white-space: nowrap;
    // }
  }

  .example {
    text-align: center;
    border-radius: 4px;

    .preview-text {
      overflow-y: auto;
      padding: 0 0 0 15px;
      height: 700px;
      text-align: left;
      white-space: pre-wrap;
    }
  }

  .modalTitle {
    overflow: hidden;
    width: 930px;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  :deep(.ant-modal-content) {
    padding: 6px;
    border-radius: 4px;
  }

  .newStatus {
    color: #f59700 !important;
  }

  :deep(.ant-tabs-nav::before) {
    display: none;
  }

  :deep(.ant-collapse) {
    border-radius: 0;
  }

  :deep(.ant-table-wrapper .ant-table-container table > thead > tr:first-child > *:first-child) {
    border-start-start-radius: 0;
  }

  :deep(.ant-table-wrapper .ant-table-container table > thead > tr:first-child > *:last-child) {
    border-start-end-radius: 0;
  }
</style>
